import React, { useState, useEffect } from 'react';
import { NavBar, Grid, Card, Image, Button, Toast, Swiper } from 'antd-mobile';
import {
    AppOutline,
    MessageOutline,
    UserOutline,
    CalendarOutline,
    LeftOutline,
    RightOutline
} from 'antd-mobile-icons';
import { history } from 'umi';
import styles from './index.less';
import { publicAPI, courseAPI } from '@/services/api';

const Home: React.FC = () => {
    const [currentPage, setCurrentPage] = useState(0);
    const [banners, setBanners] = useState<any[]>([]);
    const [courses, setCourses] = useState<any[]>([]);
    const baseUrl = 'http://localhost:3001';

    // 将课程分成每页2个
    const courseList = React.useMemo(() => {
        const pages = [];
        for (let i = 0; i < courses.length; i += 2) {
            pages.push(courses.slice(i, i + 2));
        }
        return pages;
    }, [courses]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                // 获取轮播图和课程数据
                const [bannerRes, courseRes] = await Promise.all([
                    publicAPI.getBanners(),
                    courseAPI.getCourses()
                ]);

                if (bannerRes.code === 200) {
                    const formattedBanners = bannerRes.data.map(banner => ({
                        ...banner,
                        image_url: `${baseUrl}${banner.image_url}`
                    }));
                    setBanners(formattedBanners);
                }

                if (courseRes.code === 200) {
                    const formattedCourses = courseRes.data.map(course => ({
                        ...course,
                        image: `${baseUrl}${course.image_url}`,
                        desc: course.short_desc
                    }));
                    setCourses(formattedCourses);
                }
            } catch (error) {
                console.error('Failed to fetch data:', error);
            }
        };

        fetchData();
    }, []);

    // 功能区数据
    const features = [
        { icon: <CalendarOutline />, title: '课程表' },
        { icon: <MessageOutline />, title: '通知' },
        { icon: <UserOutline />, title: '我的课程' },
        { icon: <AppOutline />, title: '更多' },
    ];

    const handlePageChange = (direction: 'prev' | 'next') => {
        if (direction === 'prev' && currentPage > 0) {
            setCurrentPage(currentPage - 1);
        } else if (direction === 'next' && currentPage < courseList.length - 1) {
            setCurrentPage(currentPage + 1);
        }
    };

    return (
        <div className={styles.container}>
            <NavBar className={styles.navbar} back={null}>
                <span className={styles.navTitle}>舞蹈艺术</span>
            </NavBar>
            
            <div className={styles.content}>
                {/* 轮播图 */}
                <div className={styles.banner}>
                    <Swiper
                        autoplay
                        loop
                        autoplayInterval={3000}
                        defaultIndex={0}
                        onIndexChange={index => {
                            // console.log('轮播图索引:', index);
                        }}
                        indicator={(total, current) => (
                            <div className={styles.customIndicator}>
                                {`${current + 1} / ${total}`}
                            </div>
                        )}
                    >
                        {banners.map(banner => (
                            <Swiper.Item key={banner.id}>
                                <div className={styles.bannerContent}>
                                    <img 
                                        src={banner.image_url} 
                                        alt={banner.title}
                                        className={styles.bannerImage}
                                        onError={(e) => {
                                            const target = e.target as HTMLImageElement;
                                            target.onerror = null;
                                            target.src = 'https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg'; // 设置默认图片
                                        }}
                                    />
                                </div>
                            </Swiper.Item>
                        ))}
                    </Swiper>
                </div>

                {/* 功能区 */}
                <Grid columns={4} gap={8} className={styles.features}>
                    {features.map((feature, index) => (
                        <Grid.Item key={index}>
                            <div className={styles.featureItem} onClick={() => console.log('Feature clicked:', feature.title)}>
                                <span className={styles.featureIcon}>{feature.icon}</span>
                                <span>{feature.title}</span>
                            </div>
                        </Grid.Item>
                    ))}
                </Grid>

                {/* 推荐课程区域 */}
                <div className={styles.courseSection}>
                    <div className={styles.sectionHeader}>
                        <h3 className={styles.sectionTitle}>推荐课程</h3>
                        <div className={styles.pageControl}>
                            <span className={styles.pageInfo}>
                                {`${currentPage + 1}/${courseList.length}`}
                            </span>
                            {courseList.length > 1 && ( // 只有当有多页时才显示翻页按钮
                                <div className={styles.pageButtons}>
                                    <Button
                                        className={styles.pageButton}
                                        onClick={() => handlePageChange('prev')}
                                        disabled={currentPage === 0}
                                    >
                                        <LeftOutline />
                                    </Button>
                                    <Button
                                        className={styles.pageButton}
                                        onClick={() => handlePageChange('next')}
                                        disabled={currentPage === courseList.length - 1}
                                    >
                                        <RightOutline />
                                    </Button>
                                </div>
                            )}
                        </div>
                    </div>
                    <div className={styles.courseList}>
                        {courseList[currentPage]?.map((course, index) => (
                            <Card 
                                key={course.id} 
                                className={styles.courseCard}
                                onClick={() => history.push(`/course-detail/${course.id}`)}
                            >
                                <Image
                                    src={course.image}
                                    className={styles.courseImage}
                                />
                                <div className={styles.courseInfo}>
                                    <h4>{course.title}</h4>
                                    <p>{course.desc}</p>
                                </div>
                            </Card>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Home;